package cc.atliberty.cookie;

import cc.atliberty.session.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ByBookServlet")
public class ByBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Book book = new Book();
        try {
            conn = DBUtil.getConnection();
            String sql = "select * from t_book where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {
                book.setId(rs.getString("id"));
                book.setName(rs.getString("name"));
                book.setAuthor(rs.getString("author"));
                book.setPrice(rs.getDouble("price"));
                book.setDesc(rs.getString("desc"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        HttpSession session = request.getSession();

        String sessionid = session.getId();
        Cookie cookie = new Cookie("JSESSIONID", sessionid);
        cookie.setMaxAge(30 * 60);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        List<Book> list = (List) session.getAttribute("list");
        if (null == list) {
            list = new ArrayList();
        }
        list.add(book);
        session.setAttribute("list", list);

        String url = response.encodeRedirectURL(request.getContextPath() + "/ListCart");
        response.sendRedirect(url);
    }
}

